#include "Mesh.h"
#pragma unmanaged
Mesh::Mesh()
{
	VBuf=NULL;
	g_pVertexBuffer=NULL;
}

Mesh::~Mesh()
{
  if(VBuf!=NULL) delete VBuf;
  if(g_pVertexBuffer!=NULL) g_pVertexBuffer->Release();
}

bool Mesh::NewMesh(Dx dx)
{
	if(VBuf!=NULL) delete VBuf;
	VBuf=new Vertex[VertexSize];
	if(g_pVertexBuffer!=NULL) g_pVertexBuffer->Release();
	D3D11_BUFFER_DESC bd;
    ZeroMemory( &bd, sizeof(bd) );
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof(Vertex) * VertexSize;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = 0;
    D3D11_SUBRESOURCE_DATA InitData;
    ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = VBuf;
    if(0 != (dx.GetDevice())->CreateBuffer( &bd, &InitData, &g_pVertexBuffer )) return false;
	Mod=true;
	return true;
}

Vertex* Mesh::GetVertex(UINT index)
{
	if(index>VertexSize-1) return NULL;
	return &(VBuf[index]);
}


void Mesh::Rendering(Dx dx)
{
	if(g_pVertexBuffer==NULL) return;
	if(Mod)
	{
		(dx.GetDeviceContext())->UpdateSubresource( g_pVertexBuffer, 0, NULL, VBuf, 0, 0 );
		Mod=false;
	}
	(dx.GetDeviceContext())->IASetPrimitiveTopology((D3D11_PRIMITIVE_TOPOLOGY) PT);
	UINT stride = sizeof( Vertex );
    UINT offset = 0;
    (dx.GetDeviceContext())->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset );
	(dx.GetDeviceContext())->IASetPrimitiveTopology((D3D11_PRIMITIVE_TOPOLOGY) PT);
	//(dx.GetDeviceContext())->Draw(VertexSize,0);
}

#pragma managed